import random
from django_redis import get_redis_connection
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from verifications import constants
from meiduomall.libs.yuntongxun.sms import CCP

# Create your views here.

# 生成日志器
import logging
logger = logging.getLogger('django')

# GET sms_codes/(?P<mobile>1[3-9]\d{9})/
class SmsCodeView(APIView):
    def get(self, request, mobile):
        """
        获取短信验证码
        1.随机生成6位手机号
        2.在redis中存储短信验证码内容
        3.使用云通讯给'mobile'发短信
        4.返回应答，短信发送成功
        """
        # 判断给'mobile'60s之内是否发过短信
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return Response({'message': '短信发送过于频繁'}, status=status.HTTP_403_FORBIDDEN)

        # 1.随机生成6位手机号
        sms_code = "%06d" % random.randint(0, 999999)
        logger.info('短信验证码的内容是：%s' % sms_code)
        # 2.在redis中存储短信验证码内容
        # redis_conn.set('<key>', '<value>', '<expires>')
        # redis_conn.setex('<key>', '<expires>', '<value>')

        # 创建redis-pipeline对象
        pl = redis_conn.pipeline()

        # 向redis管道中添加命令
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, sms_code)

        # 一次性执行管道中的所有命令
        pl.execute()

        # # 3.使用云通讯给'mobile'发短信
        expires = constants.SMS_CODE_EXPIRES // 60

        from celery_tasks.sms.tasks import send_sms_code

        send_sms_code.delay(mobile, sms_code, expires)

        # 4.返回应答，短信发送成功
        return Response({'message': 'OK'})